from PIL import Image
from PIL import ImageChops
import sys
from os import path

def compare(image1_path, image2_path, save_dir_path, threshold=30):
    """
    @参数一: image1_path:     第一张图片的路径
    @参数二: image2_path:     第二张图片的路径
    @参数三: save_dir_path:   保存标记两张图片不同之处的新图片文件夹路径
    @参数三: threshold:       阈值
    """
    image1_name = path.basename(image1_path).split('.')[0]
    image2_name = path.basename(image1_path).split('.')[0]
    save_full_path = path.join(save_dir_path, f'{image1_name}_{image2_name}_diff.png')

    image1 = Image.open(image1_path)
    image2 = Image.open(image2_path)

    if (image1.mode != "RBG"):
        image1 = image1.convert("RGB")
    if (image2.mode != "RBG"):
        image2 = image2.convert("RGB")

    try:
        image_diff = ImageChops.difference(image1, image2)

        red_channel = image_diff.getchannel(0)
        invert_red_channel = ImageChops.invert(red_channel)
        red_channel_convert_gray = invert_red_channel.convert('1')
        gray_convert_rgba = red_channel_convert_gray.convert("RGBA")
        width, height = gray_convert_rgba.size

        for i in range(0, width):
            for j in range(0, height):
                data = red_channel.getpixel((i, j))
                if (data < threshold):
                    gray_convert_rgba.putpixel((i, j), (255, 255, 255, 0))
                else:
                    gray_convert_rgba.putpixel((i, j), (255, 0, 0, 255))
                    gray_convert_rgba.paste((255, 0, 0, 255), (i - 2, j - 2, i + 2, j + 2))

        rgba_convert_rgb = gray_convert_rgba.convert("RGB")

        gray_image1 = image1.convert("L")
        gray_image1_convert_rgb = gray_image1.convert("RGB")

        green_channel = rgba_convert_rgb.getchannel(1)
        save_image = Image.composite(gray_image1_convert_rgb, rgba_convert_rgb, green_channel)

#         save_image.show()
        save_image.save(save_full_path)
        return save_full_path
        """ if diff.getbbox() is None:
            print("图片一致")
        else:
            diff.save(save_full_path) """

    except ValueError as e:
        print("【{0}".format(e))


if __name__ == '__main__':
    image1_path = sys.argv[1]
    image2_path = sys.argv[2]
    save_dir_path = sys.argv[3]
    threshold = sys.argv[4]

    print(compare(image1_path, image2_path, save_dir_path, int(threshold)))
    # compare('./compareImages/a.jpg', './compareImages/a1.jpg', './compareImages', 30)
    # compare('./compareImages/b.jpg', './compareImages/b1.jpg', './compareImages', 60)
    # compare('./compareImages/c.jpg', './compareImages/c1.jpg', './compareImages', 30)
    # compare('./compareImages/d.jpg', './compareImages/d1.jpg', './compareImages', 10)
